package com.mm.cloth.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.mm.cloth.api.ApiClient;
import com.mm.cloth.api.ApiService;
import com.mm.cloth.model.Category;
import com.mm.cloth.model.response.ApiResponse;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Token调试工具
 * 用于调试token认证问题
 */
public class TokenDebugHelper {
    
    private static final String TAG = "TokenDebugHelper";
    
    /**
     * 检查token状态
     */
    public static void checkTokenStatus(Context context) {
        Log.d(TAG, "==========================================");
        Log.d(TAG, "开始检查Token状态");
        Log.d(TAG, "==========================================");
        
        // 检查SharedPreferences中的数据
        SharedPreferences preferences = context.getSharedPreferences("user_data", Context.MODE_PRIVATE);
        
        String token = preferences.getString("token", null);
        String userId = preferences.getString("user_id", null);
        String username = preferences.getString("username", null);
        long loginTime = preferences.getLong("login_time", 0);
        
        Log.d(TAG, "SharedPreferences中的数据:");
        Log.d(TAG, "- token: " + (token != null ? "存在 (长度:" + token.length() + ")" : "不存在"));
        Log.d(TAG, "- user_id: " + userId);
        Log.d(TAG, "- username: " + username);
        Log.d(TAG, "- login_time: " + loginTime);
        
        if (token != null) {
            Log.d(TAG, "- token前20位: " + token.substring(0, Math.min(20, token.length())));
        }
        
        // 检查登录状态
        boolean isLoggedIn = TokenManager.isLoggedIn(context);
        Log.d(TAG, "TokenManager.isLoggedIn(): " + isLoggedIn);
        
        // 检查token获取
        String tokenFromManager = TokenManager.getToken(context);
        Log.d(TAG, "TokenManager.getToken(): " + (tokenFromManager != null ? "成功" : "失败"));
        
        Log.d(TAG, "==========================================");
    }
    
    /**
     * 测试分类接口的token认证
     */
    public static void testCategoryApiWithToken(Context context) {
        Log.d(TAG, "==========================================");
        Log.d(TAG, "测试分类接口的Token认证");
        Log.d(TAG, "==========================================");
        
        // 先检查token状态
        checkTokenStatus(context);
        
        // 调用分类接口
        ApiService apiService = ApiClient.getInstance().getApiService();
        
        Log.d(TAG, "开始调用分类接口...");
        
        apiService.getCategoryList().enqueue(new Callback<ApiResponse<List<Category>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<Category>>> call, Response<ApiResponse<List<Category>>> response) {
                Log.d(TAG, "=== 分类接口响应 ===");
                Log.d(TAG, "HTTP状态码: " + response.code());
                Log.d(TAG, "请求URL: " + call.request().url());
                Log.d(TAG, "请求方法: " + call.request().method());
                
                // 检查请求头
                String authHeader = call.request().header("Authorization");
                Log.d(TAG, "Authorization头: " + (authHeader != null ? authHeader.substring(0, Math.min(30, authHeader.length())) + "..." : "未设置"));
                
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<List<Category>> apiResponse = response.body();
                    Log.d(TAG, "API响应码: " + apiResponse.getCode());
                    Log.d(TAG, "API响应消息: " + apiResponse.getMessage());
                    
                    if (apiResponse.getCode() == 200 && apiResponse.getData() != null) {
                        Log.d(TAG, "✅ 分类接口调用成功，获取到 " + apiResponse.getData().size() + " 个分类");
                    } else if (apiResponse.getCode() == 401) {
                        Log.e(TAG, "❌ 认证失败，token可能无效或已过期");
                    } else {
                        Log.e(TAG, "❌ API返回错误: " + apiResponse.getCode() + " - " + apiResponse.getMessage());
                    }
                } else {
                    Log.e(TAG, "❌ HTTP请求失败: " + response.code());
                    if (response.code() == 401) {
                        Log.e(TAG, "   这通常表示token认证失败");
                    }
                }
                
                Log.d(TAG, "==========================================");
            }
            
            @Override
            public void onFailure(Call<ApiResponse<List<Category>>> call, Throwable t) {
                Log.e(TAG, "❌ 分类接口网络错误: " + t.getMessage());
                Log.d(TAG, "请求URL: " + call.request().url());
                
                String authHeader = call.request().header("Authorization");
                Log.d(TAG, "Authorization头: " + (authHeader != null ? "已设置" : "未设置"));
                
                Log.d(TAG, "==========================================");
            }
        });
    }
    
    /**
     * 模拟登录并测试token
     */
    public static void simulateLoginAndTest(Context context) {
        Log.d(TAG, "==========================================");
        Log.d(TAG, "模拟登录并测试Token");
        Log.d(TAG, "==========================================");
        
        // 模拟保存token
        String mockToken = "mock_token_12345678901234567890";
        long currentTime = System.currentTimeMillis();
        
        SharedPreferences preferences = context.getSharedPreferences("user_data", Context.MODE_PRIVATE);
        preferences.edit()
                .putString("token", mockToken)
                .putString("user_id", "test_user_123")
                .putString("username", "test_user")
                .putLong("login_time", currentTime)
                .apply();
        
        Log.d(TAG, "已保存模拟token: " + mockToken);
        
        // 延迟测试，确保数据已保存
        new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
            testCategoryApiWithToken(context);
        }, 1000);
    }
    
    /**
     * 清除token并测试
     */
    public static void clearTokenAndTest(Context context) {
        Log.d(TAG, "==========================================");
        Log.d(TAG, "清除Token并测试");
        Log.d(TAG, "==========================================");
        
        TokenManager.clearAuthInfo(context);
        Log.d(TAG, "已清除token");
        
        // 延迟测试
        new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
            testCategoryApiWithToken(context);
        }, 1000);
    }
}
